import '@/assets/css/index.css'

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

import App from './App.vue'
import router from './router'
import store from './stores'

// 如果您正在使用CDN引入，请删除下面一行。
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { useIntersectionObserver } from '@vueuse/core'

const app = createApp(App)

// 注册ElementPlusIconsVue组件
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

router.beforeEach((to, from, next) => {
  // 修改标题
  document.title = to.meta.title || '默认标题'

  // 修改 favicon
  const favicon = '/logo.svg'
  changeFavicon(favicon)

  next()
})

function changeFavicon(src) {
  let link = document.querySelector("link[rel*='icon']")
  if (!link) {
    link = document.createElement('link')
    link.rel = 'icon'
    document.getElementsByTagName('head')[0].appendChild(link)
  }
  link.href = src
}

app.use(router)
app.use(store)
app.use(ElementPlus)

app.mount('#app')

app.directive('lazyImg', {
  mounted (dom, obj) {
    const { stop } = useIntersectionObserver(
      dom,
      ([{ isIntersecting }]) => {
        if (isIntersecting) {
          dom.src = obj.value
          stop()
        }
      }
    )
  },
  updated (dom, obj) {
    dom.src = obj.value
  }
})
